package controller;

import java.sql.*;
import java.io.IOException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import model.Profile;
import webSiteDataStore.UserData;
import model.Message;
import model.User;
import utilities.ParametersValidator;
import utilities.SafeSessionAccess;

public class UserProfile extends HttpServlet
{
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                                    throws ServletException, IOException, SQLException
    {
        ParametersValidator.ValidateProgrammerParameters(request, "mode");

        String mode = request.getParameter("mode");
        if (mode.equals("dosave"))
        {
            HttpSession session = request.getSession(false);
            boolean success = ParametersValidator.ValidateUserParameters(request, "firstName", "lastName", "emailAddress");
            if (success)
            {
                User user  = (User)SafeSessionAccess.getAttribute(session, "user");
                if (user == null)
                {
                    success = ParametersValidator.ValidateUserParameters(request, "userName", "password");
                    if (success)
                    {
                        String userName = request.getParameter("userName");
                        String password = request.getParameter("password");
                        user = new User(userName, password.hashCode()); 
                        int userId = UserData.authenticateUser(user);
                        success = (userId != -1);
                        if (success)
                        {
                            user.setUserId(userId);
                            UserData.loadProfile(user);
                        }
                    }
                }
                
                if (success)
                {
                    Profile oldProfile  = user.getProfile();

                    String firstName = request.getParameter("firstName");
                    String lastName = request.getParameter("lastName");
                    String emailAddress = request.getParameter("emailAddress");
                    Profile newProfile = new Profile(user.getUserId(), firstName, lastName, emailAddress);

                    success = oldProfile.equals((Object)newProfile);
                    if (!success)
                    {
                        success = UserData.updateUserProfile(user.getUserId(), newProfile);
                        if (success)
                        {
                            user.setProfile(newProfile);
                        }
                        else
                        {
                            String messageTitle = "Profile update failure" ;
                            String messageBody = "Your profile update has failed.\nPlease try again.";
                            Message displayMessage = new Message(messageTitle, messageBody);
                            request.setAttribute("profileUpdateMessage", displayMessage);
                        }
                    }
                    else
                    {
                        // Do nothing, profiles are equal.
                    }
                }
            }
            else
            {
                ResourceBundle resources = (ResourceBundle)SafeSessionAccess.getAttribute( session, "stringResources");
            
                String messageTitle = resources.getString("TITLE_PROFILE_UPDATE_FAILURE"); 
                String messageBody = resources.getString("TEXT_PROFILE_DATA_MISSING"); 
                Message displayMessage = new Message(messageTitle, messageBody);
                request.setAttribute("profileUpdateMessage", displayMessage);
            }

            mode = success ? "view" : "edit" ;
        }


        String pageTitle = "";
        String readOnly = "";
        String submitTitle = "";
        String formAction = "";
        String buttons = "";   
        
        if (mode.equals("edit"))
        {
            pageTitle = "Edit my profile" ;
            readOnly = "";
            submitTitle =  "Save";
            formAction = "MyProfile?mode=dosave";
            buttons = "<input type='reset' value='Undo Changes'><input type='submit' value='Save Changes'>";
        }
        else if (mode.equals("view"))
        {
            pageTitle = "My profile";
            readOnly = "readonly='readonly'";
            submitTitle = "Edit";
            formAction = "MyProfile?mode=edit";
            buttons = "<input type='submit' value='Edit'>";
        }

        request.setAttribute("presentationMedium", "desktop");        
        request.setAttribute("pageTitle", pageTitle);
        request.setAttribute("readOnly", readOnly);
        request.setAttribute("submitTitle", submitTitle);
        request.setAttribute("formAction", formAction);
        request.setAttribute("buttons", buttons);

        String nextPage = "/myprofile.jsp";
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextPage);
        dispatcher.forward(request, response);
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(UserProfile.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(UserProfile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}